﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracy.DataServices;
using SharedLib.XmlDataModel;
using Tracy.DataModel;
using System.Xml;

namespace Tracy.BasicServices
{
    public class DownloadManager : XmlSettingProvider<Tracy.BasicServices.DownloadManager.DownloaderSetting>
    {
        public class DownloaderSetting : XmlDataModelWithAttributes, IHasName
        {
            /// <summary>
            /// Name of the Downloader
            /// </summary>
            public string Name
            {
                get { return Attributes["name"]; }
                set { Attributes["name"] = value; }
            }

            public string ClassName
            {
                get { return Properties ["class-name"]; }
                set { Properties["class-name"] = value; }
            }

            public DownloaderSetting() : base() { }
            public DownloaderSetting(XmlNode node) : base(node) { }

            public override string RootNodeName
            {
                get
                {
                    return "downloader";
                }
            }
        }


        public DownloadManager()
            : base(@"Settings\Downloaders.xml", "downloaders/downloader")
        {
            
        }

        private IDownloadAdapter GetDownloader(string resourceType)
        {
            XmlNode node = doc.SelectSingleNode(_itemXPath + String.Format("[resource-types/resource-type='{0}' and resource-types/resource-type/@default='true']", resourceType));
            if (node == null)
            {
                node = doc.SelectSingleNode(_itemXPath + String.Format("[resource-types/resource-type='{0}']", resourceType));
            }

            if (node != null)
            {
                DownloaderSetting setting = new DownloaderSetting(node);
                IDownloadAdapter rtn = TracyBus.Instance.RegisteredObjectService.CreateInstance<IDownloadAdapter>(setting.ClassName);
                return rtn;
            }
            return null;
        }

        public void DownloadResource(Resource resource)
        {
            IDownloadAdapter adapter = GetDownloader(resource.GetResourceType());
            if (adapter != null)
            {
                adapter.Download(resource, Tracy.Properties.Settings.Default.DefaultDownloadFolder);
            }
        }

        
    }
}
